package OperationSystem.day1208Stocket.UDP.V1;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.*;

public class Server {//服务端

    public static void main(String[] args) throws IOException {
        //1.创建server的socket
        //  内部会进行本地ip+port的绑定
        //  例子：饭店开张，提供一个大家都认识的地段 ip + port
        //        ip虽然没传，但内部会帮我们处理，把所有的ip都会绑定
        try (DatagramSocket socket = new DatagramSocket(9939)) {

            //2.开门迎客，通过循环，处理业务
            while (true) {
                //3.处理一个要求
                action(socket);
            }
        }
    }

    /**
     * 处理要求
     *
     * @param socket
     */

    private static void action(DatagramSocket socket) throws IOException {
        //1.读取客户端发来的请求

        //1.1准备一个字节数组，用来存放一会儿要读到的数据
        byte[] receiveBuffer = new byte[8192];
        //1.2把buffer封装成datagram
        DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, 0, 8192);
        //1.3读取请求
        socket.receive(receivePacket);
        //1.4从receive中返回，就意味着，有人给我发送请求了

        /*System.out.println(
                Arrays.toString(Arrays.copyOfRange(receiveBuffer, 0, receivePacket.getLength())
                ));
        */

        //需要将byte[]中的数据进行 字符集编码->String
        String request = new String(receiveBuffer, 0, receivePacket.getLength(), "UTF-8");
        System.out.printf("收到的请求是|%s|%n", request);//收到请求

        //2.进行服务---根据请求,处理业务，并生成响应
        //Version1:回显服务——echo服务
        //客户端发送什么过来，就发送回去什么
        //String response=request;

        //Version2：字典查询服务——请求是英文，响应是中文+例句 有道查询
        String response = translate(request);

        //Version3：轮盘聊天——给我发送过请求的ip+port，我会记录下来，
        // 然后再有人给我发送来新的请求时，随机选择一个ip+port发送回去
        //不保证对方还在线，所以不保证对方能收到
        //randomTalk(socket,request, receivePacket.getAddress(), receivePacket.getPort());

        //3.发送响应回去
        //Version1、2对应的服务端代码块
        byte[] sendBuffer = response.getBytes("UTF-8");
        DatagramPacket sendPacket = new DatagramPacket(sendBuffer, 0,
                sendBuffer.length,
                receivePacket.getAddress(),
                receivePacket.getPort());
        socket.send(sendPacket);

    }
    /*Version3对应的服务端代码块
    private static class Remote {//Remote用来保存客户端的ip+port
        private InetAddress address;
        private int port;

        private Remote(InetAddress address, int port) {
            this.address = address;
            this.port = port;
        }
    }

    //所有曾经给我发消息的客户端的信息——远端
    private static List<Remote> remoteList = new ArrayList<>();
    private static Random random = new Random();

    private static void randomTalk(DatagramSocket socket,String request, InetAddress address, int port) throws IOException {

        System.out.printf("之前已经有%s个客户端发送了消息%n",remoteList.size());
        if(remoteList.size()>0) {
        //随机一个下标，决定吧这个消息发给他
        int rIndex = random.nextInt(remoteList.size());
        Remote remote = remoteList.get(rIndex);
            System.out.printf("决定发送给%s客户端%n",rIndex);

        //发送消息
        byte[] sendBuffer = request.getBytes("UTF-8");
        DatagramPacket sendPacket = new DatagramPacket(sendBuffer, 0,
                sendBuffer.length,
                remote.address,
                remote.port
        );
        socket.send(sendPacket);
    }
        //发送完毕将自己加入remoteList中
        remoteList.add(new Remote(address,port));
    }
    */
    //Version2用到的内部类和一些静态代码块、方法
    private static class Result {
        String chinese;
        String sentence;

        private Result(String chinese, String sentence) {
            this.chinese = chinese;
            this.sentence = sentence;
        }
    }

    private static Map<String, Result> dictionary = new TreeMap<>();

    //静态代码块，用于初始化静态属性
    static {
        dictionary.put("dictionary", new Result("字典", "He threw my dictionary back."));
        dictionary.put("mask", new Result("口罩", "They contrived a mask again"));
    }

    private static String translate(String english) {
        //按最简单的翻译功能实现——提前保存一份字典
        Result result = dictionary.get(english);
        if (result == null) {
            return "不支持的单词.";
        }
        return String.format("%s%n%s%n", result.chinese, result.sentence);
    }
}

